<?php
namespace app\newapi\controller;

use Swoole\Client\WebSocket;
use think\Controller;
use think\Config;

class Login extends Controller
{
    /**
     * 用户登录
     * @param username 公众号appid
     * @param password 用户openid
     * @param return json
     */
    public function login(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $result = M('csuser')->field('think_csuser.*,think_author_wx_user.appid,think_author_wx_user.uid')->where('username',$data['username'])->where('password',md5($data['pwd'] . Config::get('salt')))->find();
            if($result){
                return json_encode(['status'=>1,'msg'=>'登录成功','user_info'=>$result],JSON_UNESCAPED_UNICODE);
            }else{
                return json_encode(['status'=>-1,'msg'=>'登录失败'],JSON_UNESCAPED_UNICODE);
            }
        }else{
            return json_encode(['status'=>-1,'msg'=>'错误'],JSON_UNESCAPED_UNICODE);
        }
    }

    /**
     * 在线状态
     * @param id 客服id
     * @param return boolean
     */
    public function online($id){
        $result = M('csuser')->where('id',$id)->update(['type' => 1]);
        if($result){
            $wechat_info = M('csuser')->alias('c')->field('a.id,a.uid')->where('c.id',$id)->join('think_author_wx_user a','c.auid = a.id')->find();
            $arr_data = [
                'type' => 'current_csuser_count',
                'data' => [
                    'id' => $wechat_info['id'],
                    'uid' => $wechat_info['uid'],
                ]
            ];
            sendWebSocket($arr_data);
            return json(['status'=>1,'msg'=>'登录成功']);
        }else{
            return json(['status'=>-1,'msg'=>'操作失败']);
        }
    }

    /**
     * 离线状态
     * @param id 客服id
     * @param return boolean
     */
    public function outline($id){
        $result = M('csuser')->where('id',$id)->update(['type' => 3]);
        if($result){
            $wechat_info = M('csuser')->alias('c')->field('a.id,a.uid')->where('c.id',$id)->join('think_author_wx_user a','c.auid = a.id')->find();
            $arr_data = [
                'type' => 'current_csuser_count',
                'data' => [
                    'id' => $wechat_info['id'],
                    'uid' => $wechat_info['uid'],
                ]
            ];
            sendWebSocket($arr_data);
            return json(['status'=>1,'msg'=>'退出成功']);
        }else{
            return json(['status'=>-1,'msg'=>'操作失败']);
        }
    }

    /**
     * 忙碌状态
     * @param id 客服id
     * @param return boolean
     */
    public function busy($id){
        $result = M('csuser')->where('id',$id)->update(['type' => 2]);
        if($result){
            return json(['status'=>1,'msg'=>'忙碌中']);
        }else{
            return json(['status'=>-1,'msg'=>'操作失败']);
        }
    }
}